package com.lzh.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.edu.entity.Subject;
import com.lzh.edu.entity.excel.SubjectData;
import com.lzh.edu.entity.excel.SubjectExcelListener;
import com.lzh.edu.mapper.SubjectMapper;
import com.lzh.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.edu.vo.subject.SubjectNestVo;
import com.lzh.edu.vo.subject.SubjectVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author lizuhu
 * @since 2021-04-23
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void saveSubject(MultipartFile file) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(this)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SubjectNestVo> nestList() {
        //获取一级分类
        ArrayList<SubjectNestVo> arrayList = new ArrayList<>();
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        wrapper.orderByAsc("sort","id");
        List<Subject> subjectList = baseMapper.selectList(wrapper);
        //获取二级分类
        QueryWrapper<Subject> wrapper1 = new QueryWrapper<>();
        wrapper1.ne("parent_id","0");
        wrapper1.orderByAsc("sort","id");
        List<Subject> subjectList1 = baseMapper.selectList(wrapper1);

        //封装一级分类vo数据
        int count = subjectList.size();
        for (int i = 0; i < count; i++) {
            Subject subject = subjectList.get(i);

            //创建一级类别vo对象
            SubjectNestVo subjectNestVo = new SubjectNestVo();
            BeanUtils.copyProperties(subject, subjectNestVo);
            arrayList.add(subjectNestVo);

            //封装二级分类vo数据
            ArrayList<SubjectVo> subjectVoArrayList = new ArrayList<>();
            int count2 = subjectList1.size();
            for (int j = 0; j < count2; j++) {

                Subject subject1 = subjectList1.get(j);
                if(subject.getId().equals(subject1.getParentId())){
                    //创建二级分类vo对象
                    SubjectVo subjectVo = new SubjectVo();
                    BeanUtils.copyProperties(subject1, subjectVo);
                    subjectVoArrayList.add(subjectVo);
                }
            }
            //将二级分类封装到一级分类
            subjectNestVo.setChildren(subjectVoArrayList);
        }
        return arrayList;
    }
}
